package com.bishe.admin.controller;

import com.bishe.admin.entity.User;
import com.bishe.admin.service.LoginService;
import com.bishe.admin.entity.UserDto;
import com.bishe.common.utils.JwtUtils;
import com.bishe.common.utils.MailMsg;
import com.bishe.common.utils.Result;
import jakarta.mail.MessagingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping
@RequiredArgsConstructor
public class LoginController {
    private final LoginService loginService;
    private final RedisTemplate<String, String> redisTemplate;
    @PostMapping("/login")
    public Result LoginController(@RequestBody User user) throws MessagingException {
        User login = loginService.login(user);
        if(login !=null ){
            //自定义信息
            Map<String , Object> claims = new HashMap<>();
            claims.put("id", login.getId());
            claims.put("name",login.getUserName());

            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(claims);
            return Result.success(token);
        }
        return Result.error("用户名或密码错误");
    }
    @PostMapping("/registered")
    public Result Registered(@RequestBody UserDto user) throws MessagingException {
        String code = user.getCode();
        log.info("前端输入的验证码{}", code);
        String s = redisTemplate.opsForValue().get(user.getEmail());
        log.info("从redis中获取code->{}",s);
        if(!s.equals(code))
            return Result.error("验证码错误");
        loginService.Registered(user);
        return Result.success("注册成功");
    }
}
